import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../store/user'
import routerMap from './routerMap'

const router = createRouter({
  history: createWebHistory(),
  routes: routerMap
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 初始化用户状态
  if (!userStore.isLoggedIn) {
    userStore.initUserState()
  }
  
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 需要认证的路由
    if (!userStore.isLoggedIn) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    // 不需要认证的路由
    if (to.path === '/login' && userStore.isLoggedIn) {
      // 已登录用户访问登录页，重定向到首页
      next({ path: '/' })
    } else {
      next()
    }
  }
})

export default router